#!/usr/bin/env python
# encoding: utf-8
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Twitter Social Networking viewer in 3D"""

__author__ = 'caraciol@gmail.com'
__version__ = '0.1'


import time 
import twitter
import xmlrpclib
import socket
from sets import Set
import random
from optparse import OptionParser

server_url = 'http://127.0.0.1:20738/RPC2'
screen_name = ""
api = ""
G = ""

BLUE_COLOR = "#0000CD"
RED_COLOR = "#ff0000"
GREEN_COLOR = "#00ff00"


expandedVertices = Set()
vertexes = {}
vertexes_invert = {}


def expandVertex(v):
	if v in expandedVertices:
		return 0
	
	#Added the vertice (the current root)
	expandedVertices.add(v)
	
	#Now he is loading the current friends
	G.set_vertex_attribute(v, "color", BLUE_COLOR)
	root_name = vertexes[v]
	
	print  "Getting some friends of %s..." % root_name
	friends = api.GetFriends(root_name)
	
	if len(friends) <=0:
		if vertexes[v] != screen_name:
			color_node = GREEN_COLOR
		else:
			color_node = RED_COLOR
		G.set_vertex_attribute(v, "color", color_node)
	
	for friend in friends:
		friendName = friend.GetScreenName()
	
		if vertexes_invert.get(friendName) is not None:
			edge = G.new_edge(v,vertexes_invert[friendName])
			G.set_edge_attribute(edge,"arrow", "true")
		else:
			new_vertex = G.new_vertex()
			G.set_vertex_attribute(new_vertex,"label", friendName)
			G.set_vertex_attribute(new_vertex,"shape", "sphere")
		
			vertexes.update({new_vertex: friendName})
			vertexes_invert.update({friendName: new_vertex})
			
			edge = G.new_edge(v, new_vertex)
			G.set_edge_attribute(edge,"arrow", "true")
			
	if vertexes[v] != screen_name:
		color_node = GREEN_COLOR
	else:
		color_node = RED_COLOR
		
	G.set_vertex_attribute(v, "color", color_node)
		
	return 0
		
if __name__ == "__main__":
	parser = OptionParser()
	parser.add_option("-u", "--username" , dest="username",
						help="The Twitter username", metavar="USERNAME")
	parser.add_option("-p", "--password" , dest="password", 
						help="The twitter password", metavar="PASSWORD")
	
	(options,args) = parser.parse_args()
	
	if (not options.username):
		parser.print_help()
		exit()
	
	print "Starting the TwitterNetworking3D for user %s ... " % (options.username,)
	
	screen_name = options.username
	api = twitter.Api(username=options.username,password=options.password)
	server = xmlrpclib.Server(server_url)
	

	G = server.ubigraph
	
	try:
		G.clear()
	except socket.error,msg:
		print "Error:\t Impossible to connect to the Ubigraph server. Check if the server is running.\n\tError message:%s\n" % msg
		exit()
		
	root = G.new_vertex()
	
	vertexes.update({root: screen_name})
	vertexes_invert.update({screen_name: root})
	
	G.set_vertex_attribute(root, "color" , RED_COLOR )
	G.set_vertex_attribute(root,"shape", "sphere")
	G.set_vertex_attribute(root,"label", screen_name)
	
	myPort = random.randint(20700,30000)
	G.set_vertex_style_attribute(0,"callback_left_doubleclick", "http://127.0.0.1:" + str(myPort) + "/expandVertex")
	from SimpleXMLRPCServer import SimpleXMLRPCServer
	server = SimpleXMLRPCServer(("localhost", myPort))
	server.register_introspection_functions()
	server.register_function(expandVertex)
	print "Listening for callbacks from ubigraph on the port %d ... " % (myPort,)
	server.serve_forever()




